package com.atguigu.ossservice.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.ossservice.service.FileService;
import com.atguigu.ossservice.utils.ConstantPropertiesUtil;
import com.atguigu.servicebase.VO.FrontVo;
import com.atguigu.servicebase.handler.GuliException;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.DataInput;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @program: book-shore
 * @description
 * @author: Pudding
 * @create: 2020-05-28 10:06
 **/
@Service
public class FileServiceimpl implements FileService {

    /**
     * 文件上传至阿里云
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file) {
            String endpoint = ConstantPropertiesUtil.END_POINT;
            String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
            String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
            String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
            try {
                // 创建OSSClient实例。
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

                // 上传文件流。
                InputStream inputStream = file.getInputStream();
                //使用uuid使文件名不重复
                String fileName = file.getOriginalFilename();
                String uuid = UUID.randomUUID().toString();
                fileName = uuid + fileName;


                //定义文件目录
                String path = new DateTime().toString("yyyy/MM/dd");
                fileName = path + "/" + fileName;
                ossClient.putObject(bucketName, fileName, inputStream);

                // 关闭OSSClient
                ossClient.shutdown();

                //拼接url
                //https://guli-file190919test.oss-cn-beijing.aliyuncs.com/01.jpg
                String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
                return url;
            } catch (Exception e) {
                throw new GuliException(20001,"上传失败");
            }

        }

}
